package com.bit.cfdi.web.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.SerieDAO;
import com.bit.cfdi.web.domain.DBConstants;
import com.bit.cfdi.web.domain.Negocio;
import com.bit.cfdi.web.domain.Serie;
import com.bit.cfdi.web.domain.Sucursal;

@Repository
public class SerieDAOImpl extends HibernateDaoSupport implements SerieDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) {		
		setSessionFactory(sessionFactory);
	}
	
	@Override
	@Transactional public void save(final Serie serie) throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(serie);
	}

	@Override
	@Transactional public void delete(final Serie serie) throws DataAccessException {
		getHibernateTemplate().delete(serie);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Serie> getAll() throws DataAccessException {
		List<Serie> toReturn = getHibernateTemplate().find(
				" from Serie as s");
		return toReturn;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Serie> getBySucursalRFC(Sucursal sucursal, String RFC) throws DataAccessException {
		List<Serie> toReturn = new ArrayList<Serie>();
		if(sucursal == null) {
			toReturn = getHibernateTemplate().find(
					" from Serie as s" +
					" where s.RFC=? and" +
					" s.status=?", RFC, DBConstants.STATUS_ACTIVE);
		}
		else {
			toReturn = getHibernateTemplate().find(
					" from Serie as s" +
					" where s.sucursal=? and" +
					" s.RFC=? and" +
					" s.status=?", sucursal, RFC, DBConstants.STATUS_ACTIVE);
		}
		
		return toReturn;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Serie> getAprobacionByNegocioYSerie(Negocio negocio, String serie) throws DataAccessException {
		List<Serie> aprobacion = getHibernateTemplate().find(
				"from Serie as s" +
				" where s.sucursal.negocio=? and serie=? and" +
				" s.status=?", negocio, serie, DBConstants.STATUS_ACTIVE);			
		
		return aprobacion!=null&&aprobacion.size()>0?aprobacion:null;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public Serie getBySucursalNegocioRFCSerie(final Sucursal sucursal,
			final String RFC, final String serie) throws DataAccessException {
		List<Serie> toReturn = getHibernateTemplate().find(
					" from Serie as s" +
					" where s.sucursal=?" +
					" and s.RFC=?" +
					" and s.serie=?", sucursal, RFC, serie);
		return toReturn.size()>0?toReturn.get(0):null;
	}
}
